#include "icapturestrategy.h"

static int averageValOfImg(cv::Mat frame)
{
    double pixel = 0;
    for (int i = 0; i < frame.rows; i++) {
        for (int j = 0; j < frame.cols; j++) {
            pixel += frame.at<uchar>(i,j);
        }
    }
    return pixel/(frame.rows*frame.cols);
}

cv::Mat imgMinusAvg(cv::Mat frame)
{
    // int avg = averageValOfImg(frame);
    // for (int i = 0; i < frame.rows; i++) {
    //     for (int j = 0; j < frame.cols; j++) {
    //         frame.at<uchar>(i,j) -= avg;
    //     }
    // }

    cv::Mat result;
    // subtract函数会自动处理数据类型，并且比循环快得多
    subtract(frame, mean(frame), result);

    return frame;
}

ICaptureStrategy::ICaptureStrategy(int w, int h)
    : itsWidth(w), itsHeight(h)
{

}

ICaptureStrategy::~ICaptureStrategy()
{
    if(itsVideo.isOpened())
    {
        itsVideo.release();
    }
}

int ICaptureStrategy::AnalyzeTheRainfallTrend(cv::Mat& gray)
{
    int validPixels = 0;
    cv::Mat frame3 = imgMinusAvg(gray);
    cv::imshow("after", frame3);

    return GetCurrentValidPixels(frame3, itsBaseImage);
}

int ICaptureStrategy::GetCurrentValidPixels(cv::Mat frame, cv::Mat baseFrame)
{
    int pixel = 0;
    int basePixel = 0;
    int validPixels = 0;
    // qDebug() << "frame rows : " << frame.rows << "    clos : " << frame.cols;
    // qDebug() << "baseFrame rows : " << baseFrame.rows << "    clos : " << baseFrame.cols;
    cv::Mat lastImg = cv::Mat::zeros(cv::Size(itsWidth,itsHeight),CV_8U);
    for (int i = 0; i < frame.rows; i++) {
        for (int j = 0; j < frame.cols; j++) {
            pixel = frame.at<uchar>(i,j);
            basePixel = baseFrame.at<uchar>(i,j);
            //            cout << pixel << ", base: " << basePixel << endl;
            int diff = abs(pixel - basePixel);
            validPixels += diff;
            lastImg.at<uchar>(i, j) = diff;
        }
    }
    // qDebug() << "currpixel:"<< validPixels/AREA;
    imshow("比较结果，越黑代表像素点差距越小", lastImg);
    return validPixels/(itsWidth*itsHeight)*3; // todo  放大结果
}

int ICaptureStrategy::getFrameIndex()
{
    return 0;
}

void ICaptureStrategy::setFrameIndex(int index)
{

}

int ICaptureStrategy::getFrameTotal()
{
    return 1;
}

void ICaptureStrategy::frameForward()
{
}

void ICaptureStrategy::frameBackoff()
{
}
